module.exports = app =>{
    const express = require('express')
    const bills = require('../../models/Bill')
    const router = express.Router({
        mergeParams: true
    })
    
    router.get('/bill',async (req,res)=>{
        await bills.find({},(err,bill)=>{
            err ? res.send(err) : res.send(bill)
        })
    })

    router.get('/bill/address',async (req,res)=>{
        await bills.find({address:req.query.address},(err,bill)=>{
            err ? res.send(err) : res.send(bill)
        })
    })

    router.get('/bill/time',async (req,res)=>{
        await bills.find({time:req.query.time},(err,bill)=>{
            err ? res.send(err) : res.send(bill)
        })
    })

    router.post('/bill',async(req,res)=>{
        const { address, time, goodslist } = req.body 
        var bill = await bills.findOne({address:address,time:time})
        if(bill){
            var goods = [...goodslist,...bill.goodslist]
            var goodsTotal = [];  // 存最终数据结果

            // 数据按照水果名称进行归类
            var nameContainer = {}; // 针对键name进行归类的容器
            goods.forEach(item => {
                nameContainer[item.goods] = nameContainer[item.goods] || [];
                nameContainer[item.goods].push(item);
            });

            console.log(nameContainer); // 按照水果名称归类完成：{ apple: Array(2), banana: Array(2) }

            // 统计不同种类水果的数量
            var fruitName = Object.keys(nameContainer); // 获取水果种类：["apple", "banana"]
            fruitName.forEach(nameItem => {
                let count = 0;
                nameContainer[nameItem].forEach(item => {
                    count += item.value; // 遍历每种水果中包含的条目计算总数
                });
                goodsTotal.push({'goods': nameItem, 'value': count});
            });
            await bills.updateOne({address:address,time:time},{$set:{goodslist:goodsTotal}},err=>{
                err ? res.send(err) : res.send('ok')
            })
        }else{
            await bills.create({address:address,time:time,goodslist:goodslist},err=>{
                err ? res.send(err) : res.send('ok')
            })
        }
    })

    app.use('/api/admin',router)
}